﻿using System;
using System.Data;

namespace zijian666.Data
{
    /// <summary>
    /// 自动关闭的 <see cref="IDataReader"/> 结构
    /// </summary>
    internal readonly struct SelfClosingDataReader : IDisposable
    {
        private readonly IDataReader _reader;
        private readonly IDbCommand _command;

        public SelfClosingDataReader(IDataReader reader, IDbCommand command)
        {
            _reader = reader ?? throw new ArgumentNullException(nameof(reader));
            _command = command ?? throw new ArgumentNullException(nameof(command));
        }

        public void Dispose()
        {
            if (_reader.IsClosed)
            {
                return;
            }
            if (_reader.Read() || _reader.NextResult())
            {
                // 如果datareader未读完直接dispose,将会自动读取剩下的数据后才释放
                _command.Cancel();
            }
            _reader.Close();
            _reader.Dispose();
        }
    }
}
